package com.ifighter.util;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ifighter.R;

public class Adapter extends ArrayAdapter<String> {

	private Context context                = null;
	ArrayList<String>  elements            = null;
	private ArrayList<Boolean> itemChecked = null;
	
	public ViewHolder holder;
	

	public Adapter(Context context, int type, ArrayList<String> elements) {
		super(context, type, elements);
		this.elements = elements;
		this.context  = context;
		itemChecked   = new ArrayList<Boolean>();

//		BroadcastReceiver receiver = new BroadcastReceiver() {
//			@Override
//			public void onReceive(Context context, Intent intent) {
//				if (intent.getAction().equals("master_check_change")) {
//					boolean check_value = intent.getBooleanExtra("check_value", false);
//					set_checked(check_value);
//					notifyDataSetChanged();
//				}
//			}
//		};
//		context.registerReceiver(receiver, new IntentFilter("master_check_change"));
//		set_checked(false);
	}

//	private void set_checked(boolean is_checked) {
//		for (int i=0; i < elements.size(); i++) {
//			itemChecked.add(i, is_checked);
//		}
//	}

	static class ViewHolder {
		public TextView tv;
		public CheckBox cb;
		public ImageView iv;
	}

	@Override
	public View getView (final int position, View convertView, ViewGroup parent) {

		View rowView            = convertView;
		LayoutInflater inflater = null;

		if (rowView == null) {

			inflater  = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			rowView   = inflater.inflate(R.layout.inflated_layout, null, false);
			holder    = new ViewHolder();
			holder.cb = (CheckBox) rowView.findViewById(R.id.checkBox1);
			holder.tv = (TextView) rowView.findViewById(R.id.textView1);
			holder.iv = (ImageView) rowView.findViewById(R.id.imageView1);
			rowView.setTag(holder);
		} else {
			holder = (ViewHolder) rowView.getTag();
		}

		if (holder != null) {

			holder.tv.setText(elements.get(position));
			holder.cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					if (buttonView.isChecked()) {
						Toast.makeText(context, holder.tv.getText(), Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(context, "2", Toast.LENGTH_SHORT).show();
					}
				}
			});

			if(position < itemChecked.size()) {
				holder.cb.setChecked(itemChecked.get(position));
			}
		}
		return rowView;
	}
}